{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "24.5d856d7693e4be1d6c4e49c615669bb6.2592000.1525795807.282335-11063361\n"
     ]
    }
   ],
   "source": [
    "import requests, json, os, base64\n",
    "from aip.speech import AipSpeech\n",
    "\n",
    "baidu_server = \"https://aip.baidubce.com/oauth/2.0/token?\" #获取token的地址\n",
    "grant_type = \"client_credentials\" #固定值\n",
    "client_id = 'S9XOU2PDMLo9cFh9LRdw08EU' #apiKEY\n",
    "client_secret = '31f2ca52d9b4ba558188cbd9de09b9d0' #secrenKEY\n",
    "#组合url\n",
    "url = \"%sgrant_type=%s&client_id=%s&client_secret=%s\"%(baidu_server, grant_type, client_id, client_secret)\n",
    "res = requests.post(url)\n",
    "token = json.loads(res.text)[\"access_token\"]\n",
    "print(token)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7418924\n"
     ]
    }
   ],
   "source": [
    "#设置参数\n",
    "FORMAT = 'wav'\n",
    "CUID = 'yangleidat'\n",
    "DEV_PID = '1536'\n",
    "    #读取文件并转码\n",
    "file = r'D:\\myCode\\myPythonCode\\API\\baidu\\yuyin2wenzi\\Calling_001.wav'\n",
    "with open(file, 'rb') as f:\n",
    "    speech = base64.b64encode(f.read()).decode('utf8')\n",
    "size = os.path.getsize(file)\n",
    "headers = {'Content-Type':'application/json'}\n",
    "apiurl = \"https://vop.baidu.com/server_api\"\n",
    "set_data = {\n",
    "    'format':FORMAT,\n",
    "    'rate':16000,\n",
    "    'dev_pid':DEV_PID,\n",
    "    'channel':1,\n",
    "    'token':token,\n",
    "    'cuid':CUID,\n",
    "    'len':size,\n",
    "    'speech':speech\n",
    "}\n",
    "print(size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"err_msg\":\"json speech not found.\",\"err_no\":3300,\"sn\":\"395156691651523204447\"}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "req = requests.post(apiurl, json.dumps(set_data), headers)\n",
    "print(req.text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = json.loads(req.text)\n",
    "print(result)\n",
    "res = result['uesult'][0]\n",
    "print(res)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
